package cn.codergege.utils

import okhttp3.OkHttpClient
import okhttp3.Request
import okhttp3.Response

/**
 *  递归获取有重定向行为的 resposne
 *  对 client 要求禁止默认重定向行为:
 *
client = OkHttpClient().newBuilder()
    // 禁止默认重定向
    .followRedirects(false)
    .followSslRedirects(false)
    .cookieJar(object : CookieJar {
        // 存在内存
        private val storage = ConcurrentHashMap<String, List<Cookie>>()
        override fun saveFromResponse(url: HttpUrl, cookies: MutableList<Cookie>) {
            val host = url.host() // 有些地方可能用 host 管理 cookie 不行啊... 试试 oa
            if (!cookies.isEmpty()) {
                storage[host] = cookies
            }
        }
        override fun loadForRequest(url: HttpUrl): List<Cookie> {
            val host = url.host()
            val list = storage[host]
            // 注意, 这里不能返回空
            return list ?: ArrayList<Cookie>()
        }
    }).build()
 */
fun doRedirect(client: OkHttpClient, resp: Response, userAgent: String): Response? {
    return when {
        resp.isSuccessful -> resp
        resp.isRedirect -> {
            println("${resp.code()} -- ${resp.message()}")
            val url = resp.header("location")
            var req = Request.Builder()
                .url(url!!)
                .addHeader("User-Agent", userAgent)
                .build()
            var newResp = client.newCall(req).execute()
            doRedirect(client, newResp, userAgent)
        }
        else -> {
            println("失败")
            null
        }
    }
}
